﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Security.Cryptography;
using System.Text;

namespace ManagerVerification
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            // ActivateWorkingArea("login");
        }

        short FailedCheck(string CheckName, string password)
        {
            DataSet1TableAdapters.GET_ManagerVerificationTableAdapter get_Manager = new DataSet1TableAdapters.GET_ManagerVerificationTableAdapter();

            try
            {

                SHA256 ShaM = new SHA256Managed();
                byte[] encPassword = ShaM.ComputeHash(Encoding.ASCII.GetBytes(password));

                using (var table = get_Manager.GetData(CheckName, encPassword))
                {
                    if (table.Rows.Count > 0)
                    {
                        if (Convert.ToString(table.Rows[0]["IsSuccessful"]) == "0")
                            return 1; // не совпал пароль с логином
                        else
                            return 2; //успех операции

                    }
                    else return 0; //не найден логин в таблице

                }
            }
            catch
            {
                return 0;
            }
        }

        void ActivateWorkingArea(string Manager)
        {
            WorkPanel.Visible = true;
            LoginPanel.Visible = false;
            ActiveMan.Text += Manager + "!";
            ActiveMan.Visible = true;

        }

        protected void LogInButton_Click(object sender, EventArgs e)
        {
            try
            {
                bool LogIned = false;

                string ManagerName = null;
                ManagerName = LogIn.Text;
                string ManagerPass = null;
                ManagerPass = PassWd.Value;

                this.CheckLabel.Visible = false;

                if (string.IsNullOrEmpty(ManagerName))
                {
                    this.CheckLabel.Visible = true;
                    this.CheckLabel.Text = "Неверное имя пользователя";
                    return;
                }

                if (string.IsNullOrEmpty(ManagerPass))
                {
                    this.CheckLabel.Visible = true;
                    this.CheckLabel.Text = "Неверный пароль";
                    return;
                }

                if (FailedCheck(ManagerName, ManagerPass) == 0)
                {
                    this.CheckLabel.Visible = true;
                    this.CheckLabel.Text = "Неверное имя пользователя";
                    return;
                }

                if (FailedCheck(ManagerName, ManagerPass) == 1)
                {
                    this.CheckLabel.Visible = true;
                    this.CheckLabel.Text = "Неверный пароль";
                    return;
                }

                if (FailedCheck(ManagerName, ManagerPass) == 2)
                {
                    this.CheckLabel.Visible = true;
                    this.CheckLabel.Text = "Вы успешно залогинились!";
                    LogIned = true;
                    ActivateWorkingArea(ManagerName);
                    return;
                }

            }
            catch (Exception exception)
            {
                //ExceptionHandler.HandleException(exception);
            }
        }

        protected void RegButton_Click(object sender, EventArgs e)
        {
            //WebForm2 RegForm = new WebForm2();

            Response.Redirect("RegForm.aspx");
        }

        protected void WaresBtn_Click(object sender, EventArgs e)
        {

        }

        protected void AddBtn_Click(object sender, EventArgs e)
        {
            DataSet1TableAdapters.GET_ProducersNamesTableAdapter get_Producers = new DataSet1TableAdapters.GET_ProducersNamesTableAdapter();
            AddPanel.Visible = true;
            using (var table = get_Producers.GetData())
            {
                for (int i = 0; i < table.Rows.Count; i++)
                    ProducersList.Items.Add(table[i]["Producer"].ToString());
            }

            DataSet1TableAdapters.GET_CountriesTableAdapter get_Countries = new DataSet1TableAdapters.GET_CountriesTableAdapter();
            using (var table = get_Countries.GetData())
            {
                for (int i = 0; i < table.Rows.Count; i++)
                    CountryList.Items.Add(table[i]["Country"].ToString());
            }

            DataSet1TableAdapters.GET_CategoriesTableAdapter get_Category = new DataSet1TableAdapters.GET_CategoriesTableAdapter();

            Guid ProdID = Guid.Parse("5980108d-b8fc-440a-829b-203964ced6b0");
            using (var table = get_Category.GetData(ProdID))
            {
                for (int i=0; i<table.Rows.Count; i++)
                    CathegoryList1.Items.Add(new ListItem(table[i]["Name"].ToString(), table[i]["CategoryID"].ToString()));
            }

            //Guid ParID = Guid.Parse(CathegoryList1.SelectedValue);
            //using (var table = get_Category.GetData(ParID))
            //{
            //    for (int i = 0; i < table.Rows.Count; i++)
            //        CathegoryList2.Items.Add(new ListItem(table[i]["Name"].ToString(), table[i]["CategoryID"].ToString()));
            //}


        }

        protected void AddPerfBtn_Click(object sender, EventArgs e)
        {
            AddPerfPanel.Visible = true;

        }

        protected void RedyPerfBtn_Click(object sender, EventArgs e)
        {
            DataSet1TableAdapters.ADD_ProducerTableAdapter add_Producer = new DataSet1TableAdapters.ADD_ProducerTableAdapter();

            add_Producer.GetData(nProducerName.Text);
            ProducersList.Items.Add(nProducerName.Text);
        }

        protected void ExtraFieldsBtn_Click(object sender, EventArgs e)
        {
            ExtrasPanel.Visible = true;
        }

        protected void AddCountry_Click(object sender, EventArgs e)
        {
            AddCountryPanel.Visible = true;

        }

        protected void RedyCntryBtn_Click(object sender, EventArgs e)
        {
            DataSet1TableAdapters.ADD_CountryTableAdapter add_Country = new DataSet1TableAdapters.ADD_CountryTableAdapter();

            add_Country.GetData(CountryName.Text);
            CountryList.Items.Add(CountryName.Text);
        }

        protected void CathegoryList1_TextChanged(object sender, EventArgs e)
        {
            //DataSet1TableAdapters.GET_CategoriesTableAdapter get_Category = new DataSet1TableAdapters.GET_CategoriesTableAdapter();

            ////Guid ProdID = Guid.Parse("5980108d-b8fc-440a-829b-203964ced6b0");
            //Guid ParID = Guid.Parse(CathegoryList1.SelectedValue);
            //using (var table = get_Category.GetData(ParID))
            //{
            //    for (int i = 0; i < table.Rows.Count; i++)
            //        CathegoryList2.Items.Add(new ListItem(table[i]["Name"].ToString(), table[i]["CategoryID"].ToString()));
            //}
        }

        protected void CathegoryList1_Load(object sender, EventArgs e)
        {

        }

        protected void CathegoryList1_SelectedIndexChanged(object sender, EventArgs e)
        {
            for (int i = 0; i < CathegoryList2.Items.Count; i++)
                CathegoryList2.Items.RemoveAt(i);


            DataSet1TableAdapters.GET_CategoriesTableAdapter get_Category = new DataSet1TableAdapters.GET_CategoriesTableAdapter();

            //Guid ProdID = Guid.Parse("5980108d-b8fc-440a-829b-203964ced6b0");
            Guid ParID = Guid.Parse(CathegoryList1.SelectedValue);
            using (var table = get_Category.GetData(ParID))
            {
                for (int i = 0; i < table.Rows.Count; i++)
                    CathegoryList2.Items.Add(new ListItem(table[i]["Name"].ToString(), table[i]["CategoryID"].ToString()));
            }
        }

        protected void CathegoryList1_Init(object sender, EventArgs e)
        {
            //DataSet1TableAdapters.GET_CategoriesTableAdapter get_Category = new DataSet1TableAdapters.GET_CategoriesTableAdapter();

            //Guid ParID = Guid.Parse("5980108d-b8fc-440a-829b-203964ced6b0");
            ////Guid ParID = Guid.Parse(CathegoryList1.SelectedValue);
            //using (var table = get_Category.GetData(ParID))
            //{
            //    for (int i = 0; i < table.Rows.Count; i++)
            //        CathegoryList2.Items.Add(new ListItem(table[i]["Name"].ToString(), table[i]["CategoryID"].ToString()));
            //}
        }

        protected void Button2_Click(object sender, EventArgs e)
        {
            
        }
    }
}

/*
SHA256 ShaM = new SHA256Managed();
byte[] encPassword = ShaM.ComputeHash(Encoding.ASCII.GetBytes(password));

using (var ta = Data.GET_ClientVerification)
using (var table = ta.GetData(clientName, encPassword))
{
    UsersDS.GET_ClientVerificationRow row = (UsersDS.GET_ClientVerificationRow)table.Rows[0];
    if (!row.IsClientIDNull())
    {
        ClientID = row.ClientID;
        ClientName = clientName;

        LoadClientOrder();
        return true;
    }
}

return false;*/

/*
 try
{
string clientName = this.TB_ClientName.Text;
string password = this.TB_Password.Text;
bool rememberMe = this.CB_RememberMe.Checked;

#region CheckValues

this.Lbl_LoginError.Visible = false;

if (string.IsNullOrEmpty(clientName) || !Global.CheckUserName(clientName))
{
this.Lbl_LoginError.Visible = true;
this.Lbl_LoginError.Text = "Некорректное имя пользователя";
return;
}

if (string.IsNullOrEmpty(password) || !Global.CheckUserPassword(password))
{
this.Lbl_LoginError.Visible = true;
this.Lbl_LoginError.Text = "Некорректный пароль";
return;
}

#endregion

if (!WebClient.Login(clientName, password))
{
this.Lbl_LoginError.Visible = true;
this.Lbl_LoginError.Text = "Неверное имя пользователя или пароль";
return;
}

bool createPersistentCookie = CB_RememberMe.Checked;
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
clientName,
DateTime.Now,
DateTime.Now.AddMinutes(30),
true,
WebClient.ClientID.ToString(),
FormsAuthentication.FormsCookiePath);
string encTicket = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName);
cookie.Value = encTicket;
cookie.Secure = FormsAuthentication.RequireSSL;
cookie.Domain = FormsAuthentication.CookieDomain;
cookie.HttpOnly = true;
Response.Cookies.Add(cookie);
FormsAuthentication.RedirectFromLoginPage(clientName, createPersistentCookie);

//Response.Redirect(Request.RawUrl);
return;
}
catch (Exception exception)
{
ExceptionHandler.HandleException(exception);
}
 */